/* 
 * Copyright 2014 ShangDao.Ltd  All rights reserved.
 * SiChuan ShangDao.Ltd PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * @ActEditText.java  2014-9-12 上午9:26:57 - Carson
 * @author Guzhu
 * @email:muyi126@163.com
 * @version 1.0
 */

package com.android.tiango.baba.act;

import java.sql.SQLException;
import java.util.List;

import android.animation.AnimatorSet;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.scsd.tiango.R;
import com.android.support.httpclient.HttpCallBack;
import com.android.support.httpclient.HttpClientAsync;
import com.android.support.httpclient.HttpParams;
import com.android.tiango.baba.BaBaseActivity;
import com.android.tiango.baba.cookie.HttpUrl;
import com.android.tiango.baba.cookie.ShareCookie;
import com.android.tiango.baba.db.Area;
import com.android.tiango.baba.db.AssetsDatabaseManager;
import com.android.tiango.baba.db.City;
import com.android.tiango.baba.db.DbHelper;
import com.android.tiango.baba.db.Province;
import com.android.tiango.baba.entity.AddressModel;
import com.android.tiango.baba.entity.BaseEntity;
import com.android.tiango.baba.util.CommUtil;
import com.android.tiango.baba.util.Constants;
import com.android.tiango.baba.util.ToastUtils;
import com.android.tiango.baba.view.AppTitleBar;
import com.android.tiango.baba.view.ScreenInfo;
import com.android.tiango.baba.view.WheelProvinceMain;
import com.j256.ormlite.dao.Dao;
import com.nineoldandroids.util.StringUtil;

public class ActEditAddress extends BaBaseActivity implements OnClickListener {
	private LinearLayout mUserNameLayout;
	private LinearLayout mUserPhoneLayout;
	private LinearLayout mSzAddressLayout;
	private LinearLayout mXxAddressLayout;

	//private Button mSetDAddressButton;

	private EditText mUserNameEditText;
	private EditText mUserPhoneEditText;
	private TextView mSzAddressEditText;
	private EditText mXxAddressEditText;

	// private AddressBean mBean;
	private AnimatorSet animation = null;
	final int duration = 2 * 1000;
	private DbHelper helper;
	private Intent intent;
	private AddressModel addressModel;
	private EditText mZipCodeEditText;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.layout_editaddress);
		checkIntent();

	}

	private void checkIntent() {
		intent = getIntent();
		if (intent.hasExtra(Constants.DATA)) {
			addressModel = (AddressModel) intent
					.getSerializableExtra(Constants.DATA);
			initView();
			setViewAction();
		} else {
			finish();
		}
	}

	private String initCityCode(int coutyId) {
		AssetsDatabaseManager.initManager(getApplicationContext());
		AssetsDatabaseManager mg = AssetsDatabaseManager.getManager();
		mg.getDatabase("ormlite.db");
		helper = new DbHelper(this);
		String arName = "";
		String cityName = "";
		String prName = "";
		try {
			Dao<Province, Integer> dataPro = helper.getProvinceDao();
			Dao<City, Integer> daoCityD = helper.getCityDao();
			Dao<Area, Integer> daoAreaD = helper.getAreaDao();
			List<Area> listArea = daoAreaD.queryForEq("areaId", coutyId);
			if (null != listArea && listArea.size() > 0) {
				Area arBean = listArea.get(0);
				int cityId = arBean.getCityId();
				int prId = arBean.getProvinceId();
				arName = arBean.getAreaName();
				List<City> cityList = daoCityD.queryForEq("cityId", cityId);
				if (null != cityList && cityList.size() > 0) {
					City cityBean = cityList.get(0);
					cityName = cityBean.getCityName();
					List<Province> prList = dataPro.queryForEq("provinceId",
							prId);
					if (null != prList && prList.size() > 0) {
						Province prBean = prList.get(0);
						prName = prBean.getProvinceName();
					}
				}

			}

		} catch (SQLException e) {
			e.printStackTrace();
		}
		StringBuffer sb = new StringBuffer();
		sb.append(prName);
		sb.append("  ");
		sb.append(cityName);
		sb.append("  ");
		sb.append(arName);
		sb.append("  ");
		return sb.toString();
	}

	private void initView() {
		mUserNameLayout = (LinearLayout) findViewById(R.id.ly_userName);
		mUserPhoneLayout = (LinearLayout) findViewById(R.id.ly_userPhone);
		mSzAddressLayout = (LinearLayout) findViewById(R.id.ly_szAddress);
		mXxAddressLayout = (LinearLayout) findViewById(R.id.ly_xxAddress);

		// mSetDAddressButton = (Button) findViewById(R.id.setDefault);

		// mUserNameTextView = (TextView) findViewById(R.id.tv_userName);
		// mUserPhoneTextView = (TextView) findViewById(R.id.tv_userPhone);
		// mZipCodeTextView = (TextView) findViewById(R.id.tv_zipCode);
		// mSzAddressTextView = (TextView) findViewById(R.id.tv_szAddress);
		// mXxAddressTextView = (TextView) findViewById(R.id.tv_xxAddress);

		mUserNameEditText = (EditText) findViewById(R.id.et_userName);
		mUserPhoneEditText = (EditText) findViewById(R.id.et_userPhone);
		mSzAddressEditText = (TextView) findViewById(R.id.et_szAddress);
		mXxAddressEditText = (EditText) findViewById(R.id.et_xxAddress);
		mZipCodeEditText = (EditText) findViewById(R.id.et_postcord);
		mSzAddressEditText.setOnClickListener(this);
		mTitleBar = (AppTitleBar) findViewById(R.id.titlebar);
		if (null != mTitleBar) {
			mTitleBar.setTitle("修改收获地址");
			setBackOnClickListener();
			mTitleBar.setMoreText("完成");
			mTitleBar.setMoreTextOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					saveAddress();
					
				}
			});
		}
		if (null != addressModel) {
			String areaId = addressModel.getAreaId();
			String area = initCityCode(Integer.parseInt(areaId));
			mSzAddressEditText.setText(area);
			mUserNameEditText.setText(addressModel.getShipName());
			mUserPhoneEditText.setText(addressModel.getPhoneNumber());
			mZipCodeEditText.setText(addressModel.getPostCode());
			mXxAddressEditText.setText(addressModel.getDetailAddress());

			mUserNameEditText.setSelection(mUserNameEditText.length());//
		}
	}

	private void showDialog() {
		LayoutInflater inflater = LayoutInflater.from(this);
		final View timepickerview = inflater.inflate(R.layout.province_select,
				null);
		ScreenInfo screenInfo = new ScreenInfo(this);
		final WheelProvinceMain wheelMain = new WheelProvinceMain(
				timepickerview, this);
		wheelMain.screenheight = screenInfo.getHeight();
		wheelMain.initDateTimePicker(0, 0, 0);
		new AlertDialog.Builder(this)
				.setTitle("选择地区")
				.setView(timepickerview)
				.setPositiveButton(R.string.confirm,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								int ids[] = wheelMain.getID();
								if (null != addressModel) {
									addressModel.setProvinceId(String
											.valueOf(ids[0]));
									addressModel.setCityId(String
											.valueOf(ids[1]));
									addressModel.setAreaId(String
											.valueOf(ids[2]));
								}
								mSzAddressEditText.setText(wheelMain
										.getAddress());
							}
						})
				.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						}).show();
	}

	private void setViewAction() {
		mUserNameLayout.setOnClickListener(this);
		mUserPhoneLayout.setOnClickListener(this);
		mSzAddressLayout.setOnClickListener(this);
		mXxAddressLayout.setOnClickListener(this);

		//mSetDAddressButton.setOnClickListener(this);
		mTitleBar.setTitle("收货地址");
		// mTitleBar.setMoreText(getStringValue(R.string.info_modification));
		// createAnimation();
		// mTitleBar.setMoreOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // animation.start();
		// saveAddress();
		// }
		// });
	}

	private void saveAddress() {
		String area = mSzAddressEditText.getText().toString();
		String shipName = mUserNameEditText.getText().toString().trim();
		String cellPhone = mUserPhoneEditText.getText().toString().trim();
		String street = mXxAddressEditText.getText().toString().trim();
		String postcode = mZipCodeEditText.getText().toString().trim();
		if (StringUtil.isEmpty(shipName)) {
			ToastUtils.showMessage("姓名不能为空！");
		} else if (StringUtil.isEmpty(cellPhone)
				|| !CommUtil.isMobileNO(cellPhone)) {
			ToastUtils.showMessage("手机号码不能为空或不合法！");
		} else if (StringUtil.isEmpty(area)) {
			ToastUtils.showMessage("地址不能为空！");
		} else if (StringUtil.isEmpty(street)) {
			ToastUtils.showMessage("详细地址不能为空！");
		} else if (StringUtil.isEmpty(postcode)) {
			ToastUtils.showMessage("邮编不能为空！");
		} else {
			HttpParams param = new HttpParams();
			param.put("token", ShareCookie.getToken());
			param.put("addressId", addressModel.getAddressId());
			param.put("shipName", shipName);
			param.put("provinceId", addressModel.getProvinceId());
			param.put("cityId", addressModel.getCityId());
			param.put("areaId", addressModel.getAreaId());
			param.put("detailAddress", street);
			param.put("postCode", postcode);
			param.put("phoneNumber", cellPhone);
			param.put("isDefault", addressModel.getIsDefault());

			saveAddress(param);
		}
	}

	private void saveAddress(HttpParams param) {
		showWaitingDialog();

		HttpClientAsync clientAsync = HttpClientAsync.getInstance();
		clientAsync.post(HttpUrl.getUrl(HttpUrl.UPDATEADDRESS), param,
				new HttpCallBack() {

					@Override
					public void onHttpSuccess(Object arg0) {
						
						ToastUtils.showMessage("成功！！");
						finish();
					}

					@Override
					public void onHttpStarted() {

					}

					@Override
					public void onHttpFailure(Exception arg0, String arg1) {
						dismissWaitingDialog();

					
							ToastUtils.showMessage("失败"+arg1);
						
					}
				});// , BaseEntity.class
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.ly_userName:

			break;
		case R.id.ly_userPhone:

			break;
		case R.id.ly_szAddress:

			break;
		case R.id.et_szAddress:
			showDialog();
			break;
		/*
		 * case R.id.setDefault:// 修改 saveAddress(); break;
		 */
		default:
			break;
		}

	}
}
